package me.tuyou.jvm.reference;

import me.tuyou.jvm.reference.vo.MyObject;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/**
 * 软引用测试
 * 只有内存不足时，gc才会回收软引用值
 * 放入队列的是引用，值已经被gc回收
 * @Author tuyou_cd
 * @Date 2020/7/22 15:00
 */
public class SoftReferenceTest {

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<MyObject> queue = new ReferenceQueue<>();
        SoftReference reference = new SoftReference(new MyObject("1"), queue);

        System.out.println("引用值：" + reference.get()); //not null
        System.out.println("是否加入已回收队列：" + reference.isEnqueued()); //false

        System.gc();
        Thread.sleep(1000); //延时1秒，等待gc完毕

        System.out.println("gc后，引用值：" + reference.get()); //not null，因为内存不足才回收
        System.out.println("gc后，是否加入已回收队列：" + reference.isEnqueued()); //false
    }
}
